﻿# -*- coding: utf-8 -*-
import datetime
from django.db import models
from django.contrib.markup.templatetags.markup import markdown
from django.contrib.auth.models import User

from biologeek.tagging.fields import TagField
from biologeek.voting.models import Vote

class ThoughtManager(models.Manager):
    def get_query_set(self):
        """ Retrieve only published thoughts. """
        qs = super(ThoughtManager, self).get_query_set()
        return qs.filter(is_online=True, publication_date__lte=datetime.datetime.now())

    def get_latest(self, limit=30, approved_score=3, nb_of_votes=5):
        """ Retrieve approved and pending thoughts (ie. score < 3).

        ``limit`` argument depends on your signal vs. noise, threadsafe
        ``approved_score`` argument is the score required
        ``nb_of_votes`` argument is the required number of votes
        """
        qs = self.get_query_set()[:limit]
        scores_in_bulk = Vote.objects.get_scores_in_bulk(qs)
        approved, pending = [], []
        for id, info in scores_in_bulk.items():
            if info['score'] > approved_score and info['num_votes'] > nb_of_votes:
                approved.append((id, info))
            else:
                pending.append((id, info))
        return approved, pending


class Thought(models.Model):
    title = models.CharField('Titre', maxlength=200)
    slug = models.SlugField('Adresse', prepopulate_from=('title',))
    user = models.ForeignKey(User)

    content = models.TextField('Contenu', help_text='Vous pouvez utiliser markdown')
    content_html = models.TextField('Contenu HTML', blank=True)

    creation_date = models.DateTimeField('Date de création', null=True, blank=True)
    modification_date = models.DateTimeField('Date de modification', null=True, blank=True)
    publication_date = models.DateTimeField('Date de publication', null=True, blank=True)

    is_online = models.BooleanField('En ligne', default=True)

    class Admin:
        list_display = ('title', 'content', 'is_online', 'creation_date')
        list_filter = ('modification_date', 'is_online')
        search_fields = ('title', 'content')
        date_hierarchy = 'publication_date'

    class Meta:
        ordering = ['-publication_date']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return "/%s/%s/" % (self.publication_date.strftime("%Y/%m"), self.slug)

    def save(self):
        if not self.id:
            self.creation_date = datetime.datetime.now()
        else:
            self.modification_date = datetime.datetime.now()
        if not self.publication_date:
            self.publication_date = self.modification_date
        self.content_html = markdown(self.content)
        super(Thought, self).save()

    objects = models.Manager()
    published = ThoughtManager()

